<template>
  <div class="knowledge-map-container">
    <div class="page-header">
      <h1>知识思维导图</h1>
      <p>可视化知识结构，建立知识连接</p>
    </div>
    
    <div class="map-content">
      <div class="map-sidebar">
        <div class="sidebar-header">
          <h3>学科分类</h3>
        </div>
        
        <el-menu
          :default-active="currentSubject"
          class="subject-menu"
          @select="handleSubjectSelect"
        >
          <el-menu-item v-for="subject in subjects" :key="subject.id" :index="subject.id.toString()">
            <el-icon><component :is="subject.icon" /></el-icon>
            <span>{{ subject.name }}</span>
          </el-menu-item>
        </el-menu>
      </div>
      
      <div class="map-main">
        <div class="map-controls">
          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索知识点..."
              prefix-icon="Search"
              clearable
              @input="handleSearch"
            ></el-input>
          </div>
          
          <div class="view-controls">
            <el-radio-group v-model="viewMode" size="small">
              <el-radio-button label="mindmap">思维导图</el-radio-button>
              <el-radio-button label="tree">树形视图</el-radio-button>
            </el-radio-group>
            
            <el-button-group class="zoom-controls">
              <el-button size="small" @click="zoomIn">
                <el-icon><ZoomIn /></el-icon>
              </el-button>
              <el-button size="small" @click="zoomOut">
                <el-icon><ZoomOut /></el-icon>
              </el-button>
              <el-button size="small" @click="resetZoom">
                <el-icon><FullScreen /></el-icon>
              </el-button>
            </el-button-group>
          </div>
        </div>
        
        <div class="map-visualization">
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="10" animated />
          </div>
          
          <div v-show="viewMode === 'mindmap'" class="mindmap-container">
            <div id="mindmap-container" style="width:100%;height:100%;"></div>
          </div>
          
          <div v-show="viewMode === 'tree'" class="tree-view">
            <el-tree
              :data="treeData"
              :props="defaultProps"
              :expand-on-click-node="false"
              :default-expanded-keys="[currentSubject]"
              node-key="id"
              highlight-current
              @node-click="handleNodeClick"
            >
              <template #default="{ node, data }">
                <span class="tree-node">
                  <span>{{ node.label }}</span>
                  <span v-if="data.count" class="node-count">({{ data.count }})</span>
                </span>
              </template>
            </el-tree>
          </div>
        </div>
      </div>
      
      <div class="knowledge-detail" v-if="selectedNode">
        <div class="detail-header">
          <h3>{{ selectedNode.name }}</h3>
          <el-button size="small" @click="closeDetail">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        
        <div class="detail-content">
          <div class="detail-section">
            <h4>概述</h4>
            <p>{{ selectedNode.description }}</p>
          </div>
          
          <div class="detail-section" v-if="selectedNode.keyPoints && selectedNode.keyPoints.length">
            <h4>关键点</h4>
            <ul>
              <li v-for="(point, index) in selectedNode.keyPoints" :key="index">
                {{ point }}
              </li>
            </ul>
          </div>
          
          <div class="detail-section" v-if="selectedNode.relatedCourses && selectedNode.relatedCourses.length">
            <h4>相关课程</h4>
            <div class="related-courses">
              <el-card 
                v-for="course in selectedNode.relatedCourses" 
                :key="course.id"
                class="related-course-card"
                shadow="hover"
                @click="navigateToCourse(course.id)"
              >
                <div class="course-info">
                  <div class="course-title">{{ course.title }}</div>
                  <div class="course-meta">
                    <el-rate v-model="course.rating" disabled text-color="#ff9900" :size="14" />
                    <span class="course-students">{{ course.students }}人学习</span>
                  </div>
                </div>
              </el-card>
            </div>
          </div>
        </div>                                                                                                                                                                                                
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, nextTick, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
import MindMap from 'simple-mind-map';
import { Search, ZoomIn, ZoomOut, FullScreen, Close } from '@element-plus/icons-vue';

const router = useRouter();
const store = useStore();

const currentSubject = ref('1'); // 默认选中数学
const viewMode = ref('mindmap'); // 默认使用思维导图视图
const searchKeyword = ref('');
const loading = ref(true);
const mindMap = ref(null);
const selectedNode = ref(null);

// 学科列表
const subjects = [
  { id: 1, name: '数学', icon: 'DataAnalysis' },
  { id: 2, name: '物理', icon: 'Histogram' },
  { id: 3, name: '化学', icon: 'Monitor' },
  { id: 4, name: '生物', icon: 'Opportunity' },
  { id: 5, name: '语文', icon: 'Reading' },
  { id: 6, name: '英语', icon: 'ChatDotRound' }
];

// 树形视图配置
const defaultProps = {
  children: 'children',
  label: 'name'
};

// 模拟知识图谱数据
const knowledgeData = {
  1: { // 数学
    id: 1,
    name: '数学',
    description: '数学是研究数量、结构、变化以及空间模型等概念的一门学科。',
    children: [
      {
        id: 101,
        name: '代数',
        description: '代数是数学的一个主要分支，处理数学符号和处理这些符号的规则。',
        children: [
          {
            id: 10101,
            name: '基本运算',
            description: '包括加减乘除等基本数学运算。',
            keyPoints: [
              '加法和减法是最基本的数学运算',
              '乘法可以看作是重复的加法',
              '除法是乘法的逆运算'
            ],
            relatedCourses: [
              { id: 1, title: '小学数学 - 基础运算', rating: 4.5, students: 1200 },
              { id: 2, title: '趣味数学 - 巧算100例', rating: 4.8, students: 850 }
            ]
          },
          {
            id: 10102,
            name: '方程式',
            description: '方程式是由一个或多个变量组成的等式。',
            keyPoints: [
              '一次方程只有一个未知数且指数为1',
              '二次方程的未知数最高指数为2',
              '方程组是多个方程的集合'
            ],
            relatedCourses: [
              { id: 3, title: '初中数学 - 方程式解法', rating: 4.6, students: 980 },
              { id: 4, title: '高中数学 - 复杂方程求解', rating: 4.7, students: 760 }
            ]
          },
          {
            id: 10103,
            name: '函数',
            description: '函数描述了输入值与输出值之间的关系。',
            keyPoints: [
              '函数是从一个集合到另一个集合的映射',
              '函数可以用代数式、表格或图形表示',
              '常见函数包括线性函数、二次函数等'
            ],
            relatedCourses: [
              { id: 5, title: '高中数学 - 函数与图像', rating: 4.9, students: 1050 },
              { id: 6, title: '数学分析 - 初等函数', rating: 4.7, students: 630 }
            ]
          }
        ]
      },
      {
        id: 102,
        name: '几何',
        description: '几何是研究形状、大小、空间性质以及物体相对位置的数学分支。',
        children: [
          {
            id: 10201,
            name: '平面几何',
            description: '研究二维空间中的点、线、面等几何图形。',
            keyPoints: [
              '点、线、面是平面几何的基本元素',
              '三角形、四边形、圆是基本图形',
              '相似形和全等形具有特定的性质'
            ],
            relatedCourses: [
              { id: 7, title: '初中数学 - 平面几何基础', rating: 4.5, students: 920 },
              { id: 8, title: '高中数学 - 解析几何', rating: 4.6, students: 780 }
            ]
          },
          {
            id: 10202,
            name: '立体几何',
            description: '研究三维空间中的几何形体。',
            keyPoints: [
              '常见立体图形包括棱柱、棱锥、圆柱、圆锥和球',
              '体积和表面积是重要的度量',
              '三视图可以表示立体图形'
            ],
            relatedCourses: [
              { id: 9, title: '高中数学 - 立体几何', rating: 4.7, students: 850 },
              { id: 10, title: '空间几何 - 进阶课程', rating: 4.8, students: 560 }
            ]
          }
        ]
      },
      {
        id: 103,
        name: '统计与概率',
        description: '统计学研究数据的收集、分析、解释和呈现，概率论研究随机现象的数学分支。',
        children: [
          {
            id: 10301,
            name: '描述统计',
            description: '通过图表和数值描述数据的集中趋势和离散程度。',
            keyPoints: [
              '平均数、中位数和众数是集中趋势的度量',
              '方差和标准差是离散程度的度量',
              '直方图、饼图和折线图是常用的统计图表'
            ],
            relatedCourses: [
              { id: 11, title: '初中数学 - 统计入门', rating: 4.4, students: 720 },
              { id: 12, title: '高中数学 - 统计分析', rating: 4.6, students: 680 }
            ]
          },
          {
            id: 10302,
            name: '概率论',
            description: '研究随机事件发生的可能性。',
            keyPoints: [
              '概率的基本性质和计算规则',
              '条件概率和贝叶斯定理',
              '随机变量和概率分布'
            ],
            relatedCourses: [
              { id: 13, title: '高中数学 - 概率基础', rating: 4.7, students: 790 },
              { id: 14, title: '大学数学 - 概率论与数理统计', rating: 4.8, students: 520 }
            ]
          }
        ]
      }
    ]
  },
  // 其他学科数据...
};

// 计算属性：树形数据
const treeData = computed(() => {
  const subjectId = parseInt(currentSubject.value);
  return knowledgeData[subjectId] ? [knowledgeData[subjectId]] : [];
});

// 计算属性：过滤后的树形数据
const filteredTreeData = computed(() => {
  if (!searchKeyword.value) return treeData.value;
  
  const keyword = searchKeyword.value.toLowerCase();
  
  // 递归过滤函数
  const filterNodes = (nodes) => {
    return nodes.filter(node => {
      const nameMatch = node.name.toLowerCase().includes(keyword);
      const descMatch = node.description && node.description.toLowerCase().includes(keyword);
      
      let filteredChildren = [];
      if (node.children && node.children.length) {
        filteredChildren = filterNodes(node.children);
      }
      
      // 复制节点，避免修改原始数据
      const newNode = { ...node };
      if (filteredChildren.length) {
        newNode.children = filteredChildren;
      } else {
        delete newNode.children;
      }
      
      return nameMatch || descMatch || filteredChildren.length > 0;
    });
  };
  
  return filterNodes(treeData.value);
});

// 缩放相关方法
const zoomIn = () => {
  try {
    if (mindMap.value) {
      // 使用内置命令
      mindMap.value.execCommand('zoomIn');
    }
  } catch (error) {
    console.error('缩放失败:', error);
  }
};

const zoomOut = () => {
  try {
    if (mindMap.value) {
      // 使用内置命令
      mindMap.value.execCommand('zoomOut');
    }
  } catch (error) {
    console.error('缩放失败:', error);
  }
};

const resetZoom = () => {
  try {
    if (mindMap.value) {
      // 使用内置命令
      mindMap.value.execCommand('resetZoom');
    }
  } catch (error) {
    console.error('重置缩放失败:', error);
  }
};

// 初始化思维导图
const initMindMap = () => {
  loading.value = true;
  
  try {
    // 获取容器元素
    const container = document.getElementById('mindmap-container');
    if (!container) {
      console.error('思维导图容器元素不存在');
      loading.value = false;
      return;
    }
    
    // 清空容器
    container.innerHTML = '';
    
    // 获取当前学科的数据
    const subjectData = knowledgeData[currentSubject.value];
    if (!subjectData) {
      console.error('未找到学科数据');
      loading.value = false;
      return;
    }
    
    // 转换数据为思维导图格式
    const data = convertToMindMapData(subjectData);
    
    // 创建思维导图实例
    mindMap.value = new MindMap({
      el: container,
      data: data,
      layout: 'logicalStructure', // 逻辑结构布局
      theme: {
        background: '#f5f7fa',
        color: '#303133',
        lineColor: '#909399',
        lineWidth: 2,
        fontSize: 14,
        rootBackground: '#409EFF',
        rootColor: '#fff',
        secondNodeBackground: '#67C23A',
        secondNodeColor: '#fff',
        thirdNodeBackground: '#E6A23C',
        thirdNodeColor: '#fff'
      },
      enableFreeDrag: true, // 允许自由拖动
      watermark: {
        content: 'AI Study', // 水印内容
        opacity: 0.1 // 水印透明度
      }
    });
    
    // 注册节点点击事件
    mindMap.value.on('node_click', (node) => {
      handleMindMapNodeClick(node);
    });
    
    // 完成加载
    loading.value = false;
  } catch (error) {
    console.error('初始化思维导图失败:', error);
    loading.value = false;
  }
};

// 转换数据为思维导图格式
const convertToMindMapData = (data) => {
  // simple-mind-map 需要的数据格式
  const convertNode = (node) => {
    const result = {
      data: {
        id: node.id.toString(),
        text: node.name,
        expand: true, // 默认展开
        nodeData: node // 保存原始节点数据，用于点击事件
      },
      children: []
    };
    
    if (node.children && node.children.length) {
      result.children = node.children.map(child => convertNode(child));
    }
    
    return result;
  };
  
  return convertNode(data);
};

// 处理思维导图节点点击
const handleMindMapNodeClick = (node) => {
  // 获取节点原始数据
  const nodeData = node.data.nodeData;
  if (nodeData) {
    selectedNode.value = nodeData;
  }
};

// 处理学科选择
const handleSubjectSelect = (index) => {
  currentSubject.value = index;
  selectedNode.value = null;
  
  // 重新初始化思维导图
  if (viewMode.value === 'mindmap') {
    nextTick(() => {
      initMindMap();
    });
  }
};

// 处理视图模式切换
watch(viewMode, (newMode) => {
  if (newMode === 'mindmap') {
    nextTick(() => {
      initMindMap();
    });
  }
});

// 处理搜索
const handleSearch = () => {
  if (viewMode.value === 'mindmap' && mindMap.value) {
    // 在思维导图中搜索
    if (searchKeyword.value) {
      try {
        // 使用 simple-mind-map 的搜索方法
        const result = mindMap.value.search(searchKeyword.value.toLowerCase());
        if (result && result.length > 0) {
          // 可以高亮搜索结果或定位到第一个结果
          mindMap.value.focusNode(result[0]);
        }
      } catch (error) {
        console.error('搜索失败:', error);
      }
    }
  }
};

// 处理树节点点击
const handleNodeClick = (data) => {
  selectedNode.value = data;
};

// 关闭详情面板
const closeDetail = () => {
  selectedNode.value = null;
};

// 导航到课程
const navigateToCourse = (courseId) => {
  router.push(`/course/${courseId}`);
};

// 窗口大小变化处理
const handleResize = () => {
  if (mindMap.value) {
    try {
      // 调整思维导图大小
      mindMap.value.resize();
    } catch (error) {
      console.error('调整大小失败:', error);
    }
  }
};

// 组件挂载时
onMounted(() => {
  // 初始化思维导图
  if (viewMode.value === 'mindmap') {
    nextTick(() => {
      initMindMap();
    });
  }
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize);
});

// 组件卸载时
onUnmounted(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize);
  
  // 销毁思维导图实例
  if (mindMap.value) {
    try {
      mindMap.value.destroy();
    } catch (error) {
      console.error('销毁思维导图实例失败:', error);
    }
    mindMap.value = null;
  }
});
</script>

<style lang="scss" scoped>
.knowledge-map-container {
  padding: 20px;
  
  .page-header {
    margin-bottom: 20px;
    
    h1 {
      margin: 0 0 10px;
      font-size: 24px;
      color: #303133;
    }
    
    p {
      margin: 0;
      color: #606266;
    }
  }
  
  .map-content {
    display: flex;
    height: calc(100vh - 150px);
    border: 1px solid #ebeef5;
    border-radius: 4px;
    overflow: hidden;
    
    .map-sidebar {
      width: 200px;
      border-right: 1px solid #ebeef5;
      background-color: #fff;
      
      .sidebar-header {
        padding: 15px;
        border-bottom: 1px solid #ebeef5;
        
        h3 {
          margin: 0;
          font-size: 16px;
          color: #303133;
        }
      }
      
      .subject-menu {
        border-right: none;
      }
    }
    
    .map-main {
      flex: 1;
      display: flex;
      flex-direction: column;
      background-color: #fff;
      
      .map-controls {
        padding: 15px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #ebeef5;
        
        .search-box {
          width: 250px;
        }
        
        .view-controls {
          display: flex;
          align-items: center;
          
          .zoom-controls {
            margin-left: 15px;
          }
        }
      }
      
      .map-visualization {
        flex: 1;
        position: relative;
        
        .loading-container {
          padding: 20px;
        }
        
        .mindmap-container {
          width: 100%;
          height: 100%;
          overflow: hidden;
        }
        
        .tree-view {
          padding: 20px;
          height: 100%;
          overflow: auto;
          
          .tree-node {
            display: flex;
            align-items: center;
            
            .node-count {
              margin-left: 5px;
              color: #909399;
              font-size: 12px;
            }
          }
        }
      }
    }
    
    .knowledge-detail {
      width: 300px;
      border-left: 1px solid #ebeef5;
      background-color: #f5f7fa;
      overflow-y: auto;
      
      .detail-header {
        padding: 15px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #ebeef5;
        background-color: #fff;
        
        h3 {
          margin: 0;
          font-size: 16px;
          color: #303133;
        }
      }
      
      .detail-content {
        padding: 15px;
        
        .detail-section {
          margin-bottom: 20px;
          
          h4 {
            margin: 0 0 10px;
            font-size: 14px;
            color: #303133;
          }
          
          p {
            margin: 0;
            color: #606266;
            line-height: 1.6;
          }
          
          ul {
            margin: 0;
            padding-left: 20px;
            
            li {
              color: #606266;
              line-height: 1.6;
            }
          }
          
          .related-courses {
            .related-course-card {
              margin-bottom: 10px;
              cursor: pointer;
              
              &:last-child {
                margin-bottom: 0;
              }
              
              .course-info {
                .course-title {
                  font-weight: 500;
                  margin-bottom: 5px;
                  color: #303133;
                }
                
                .course-meta {
                  display: flex;
                  align-items: center;
                  justify-content: space-between;
                  
                  .course-students {
                    font-size: 12px;
                    color: #909399;
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .map-content {
    flex-direction: column;
    
    .map-sidebar {
      width: 100%;
      border-right: none;
      border-bottom: 1px solid #ebeef5;
    }
    
    .knowledge-detail {
      width: 100%;
      border-left: none;
      border-top: 1px solid #ebeef5;
    }
  }
}
</style> 